using Kickball.Step1;
using Kickball.Step2;
using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

namespace Kickball.Step3
{
    public partial struct BallSpawnerSystem : ISystem
    {
        Unity.Mathematics.Random mRandom;
        
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.BallSpawner>();
            state.RequireForUpdate<Config>();
            mRandom = new Unity.Mathematics.Random(123);
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            if (!Input.GetKeyDown(KeyCode.KeypadEnter)) return;
            
            var config = SystemAPI.GetSingleton<Config>();

            foreach (var playerTrans in SystemAPI.Query<RefRO<LocalTransform>>().WithAll<Player>())
            {
                var ball = state.EntityManager.Instantiate(config.BallPrefab);
                state.EntityManager.SetComponentData(ball, new LocalTransform()
                {
                    Position = playerTrans.ValueRO.Position,
                    Scale = 1,
                    Rotation = quaternion.identity,
                });
                //随机初始速度
                state.EntityManager.SetComponentData(ball, new Velocity()
                {
                    Value = mRandom.NextFloat2Direction() * config.BallStartVelocity,
                });
            }
        }
    }
}